package com.caijinbang.study.aop;

import com.caijinbang.study.annotation.ReadOnlyConnection;
import com.caijinbang.study.holder.DbContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

/**
 * Spring AOP对只读注解进行拦截
 *
 * @author caijb
 * @version 1.0.0
 * @date 2018-05-02 15:58
 */
@Aspect
@Component
@Slf4j
public class ReadOnlyConnectionInterceptor implements Ordered {

    /**
     * 通过aop拦截带有@readOnlyConnection的注解
     *
     * @param proceedingJoinPoint 连接点对象
     * @param readOnlyConnection  只读链接
     * @return
     * @throws Throwable
     */
    @Around("@annotation(readOnlyConnection)")
    public Object proceed(ProceedingJoinPoint proceedingJoinPoint, ReadOnlyConnection readOnlyConnection) throws Throwable {
        try {
            log.info("set database connection to read only");
            DbContextHolder.setDbType(DbContextHolder.DbType.SLAVE);
            Object result = proceedingJoinPoint.proceed();
            return result;
        } finally {
            DbContextHolder.clearDbType();
            log.info("restore database connection");
        }
    }

    /**
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
